<script setup lang="tsx">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { Space, Link, MessagePlugin } from 'tdesign-vue-next';
import { AddIcon } from 'tdesign-icons-vue-next';
import { getGradeList, add, edit, getInfo, Delete } from '@/api/member/level';
const { t } = useI18n();

// 公共等级列表
import { useGradeStore } from '@/store/modules/member';
const gradeStore = useGradeStore();

const data = ref([]);

const columns = [
  {
    title: '等级名称',
    colKey: 'name',
  },
  {
    title: '等级',
    colKey: 'grade',
  },
  {
    title: '售价',
    colKey: 'amount',
  },
  {
    title: '每日任务数',
    colKey: 'number',
  },
  {
    title: '任务单价',
    colKey: 'commission',
  },
  {
    title: '最低提现',
    colKey: 'withdraw',
  },
  {
    title: '推荐返佣',
    colKey: 'spread',
  },
  {
    title: '升级VIP人数',
    colKey: 'upgradeVipNum',
  },
  {
    title: '状态',
    colKey: 'state',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
    </OperatingBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      rowKey="grade"
      onUnGetList={unGetList}
    >
      {{
        amount: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.amount,
            )}
          </div>
        ),
        commission: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.commission,
            )}
          </div>
        ),
        withdraw: (slotProps: any) => (
          <div>
            {new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
              slotProps.row.withdraw,
            )}
          </div>
        ),
        state: (slotProps: any) => (
          <t-switch
            key={slotProps.row.grade}
            value={slotProps.row.state}
            onChange={() => unEditState(slotProps)}
            size="large"
            customValue={[1, 0]}
            label={['正常', '关闭']}
          ></t-switch>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

// 修改状态
const unEditState = async (slotProps: any) => {
  slotProps.row.state = slotProps.row.state == 1 ? 0 : 1;
  edit(slotProps.row).then(() => {
    MessagePlugin.success('操作成功');
    unGetList();
  });
};

const unGetList = async () => {
  try {
    const res = await getGradeList({
      pageNum: pagination.value.defaultCurrent,
      pageSize: pagination.value.defaultPageSize,
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
    gradeStore.loaded = false;
    gradeStore.fetchGradeList();
  } catch (e) {
    console.log(e);
  }
};

unGetList();

/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    formObj.show('添加等级', {}, '添加等级');
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '添加等级',
  '添加等级',
  {},
  async (body) => {
    await add(body.data);
    unGetList();
  },
  {},
);

// 详情
const unEdit = async (slotProps: any) => {
  try {
    let res = await getInfo(slotProps.row.mlId);
    formObj.show(
      '编辑等级',
      {
        ...res.data,
      },
      '编辑等级',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '编辑等级',
  '编辑等级',
  {},
  async (body) => {
    await edit(body.data);
    unGetList();
  },
  {},
);

// 删除
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  let ids = deleteId.value.join(',');
  Delete(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;
  deleteId.value = isSingle ? value : [value.row.mlId];
};
</script>

<template>
  <div>
    <render />
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 添加等级对话框 -->
        <template v-if="item == '添加等级' || item == '编辑等级'">
          <t-form-item label="等级名称" name="name">
            <t-input v-model="formData.name" placeholder="请输入等级名称" />
          </t-form-item>
          <t-form-item label="等级" name="grade" help="不能与已有等级重复">
            <div class="capital">
              <t-input-number align="left" v-model="formData.grade" placeholder="请输入等级" />
            </div>
          </t-form-item>
          <t-form-item label="售价" name="amount" help="如：300">
            <div class="capital">
              <t-input-number align="left" v-model="formData.amount" placeholder="请输入售价" suffix="元" />
            </div>
          </t-form-item>
          <t-form-item label="任务次数" name="number">
            <div class="capital">
              <t-input-number align="left" v-model="formData.number" placeholder="请输入任务次数" suffix="次/天" />
            </div>
          </t-form-item>
          <t-form-item label="任务单价" name="commission">
            <div class="capital">
              <t-input-number align="left" v-model="formData.commission" placeholder="请输入任务单价" suffix="元/单" />
            </div>
          </t-form-item>
          <t-form-item label="有效期" name="validityDay">
            <!-- <t-select v-model="formData.validityDay" :style="{ width: '440px' }" placeholder="请选择有效期">
              <t-option key="2天" label="2天" value="2" />
              <t-option key="3天" label="3天" value="3" />
              <t-option key="4个月" label="4个月" value="120" />
              <t-option key="一年" label="一年" value="365" />
            </t-select> -->
            <div class="capital">
              <t-input-number align="left" v-model="formData.validityDay" placeholder="请输入有效期" suffix="天" />
            </div>
          </t-form-item>
          <t-form-item label="升级VIP人数" name="upgradeVipNum" help="升级所需团队VIP人数">
            <div class="capital">
              <t-input-number
                align="left"
                v-model="formData.upgradeVipNum"
                placeholder="请输入升级所需直推VIP人数"
                suffix="人"
              />
            </div>
          </t-form-item>
          <t-form-item label="推荐返佣" name="spread" help="如：直推,间推,间间推 20,10,5">
            <t-input v-model="formData.spread" placeholder="请输入推荐返佣" />
          </t-form-item>
          <t-form-item label="最低提现" name="withdraw" help="如：第1次,第2次,第3次... 100,500,1000...">
            <t-input v-model="formData.withdraw" placeholder="请输入最低提现金额" />
          </t-form-item>
          <t-form-item label="状态" name="state">
            <t-select v-model="formData.state" :style="{ width: '440px' }" placeholder="请选择状态">
              <t-option :key="1" label="正常" :value="1" />
              <t-option :key="0" label="关闭" :value="0" />
            </t-select>
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选项目？"
      body="删除后，数据将被清空，且无法恢复"
      @confirm="onConfirmDelete"
    />
  </div>
</template>

<style lang="less" scoped>
.capital .t-input-number.t-input-number--row {
  width: 314px;
  display: flex;
  align-items: center;
  padding: 0 38px;

  .t-button.t-button--variant-outline.t-button--theme-default.t-button--shape-square.t-button--icon-only {
    width: 38px;
    height: 38px;
  }
}
</style>
<style>
.capital .t-input-number .t-input.t-align-center {
  width: 230px !important;
}
.capital .t-input-number .t-input {
  width: 230px !important;
}
</style>
